<?php
/**
 * 小区模型
 */

namespace app\api\model;

use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use custom\Err;
use custom\Token;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;

class HouseVillage extends Model {

    /**
     * 获取小区房源列表
     * @des
     * @param $map
     * @param $column
     * @param $page
     * @param $size
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function get_list($start, $long, $params, &$page, &$pageNum, &$data, &$count) {
        $city_code = $params['city_code'];
        //默认当前区域
        $p_codes = db('region')
            ->where('city_code', $city_code)
            ->where('rank', 2)
            ->value('p_codes');
        $city_codes = $p_codes . $city_code . ',';
        $map = [];
        $map[] = ['hv.city_codes', 'like', $city_codes . '%'];
        if (!empty($params['vname'])) {
            $map[] = ['hv.name', 'like', '%' . trim($params['vname']) . '%'];
        }
        $column = ['hv.name', 'hv.total_num', 'hv.id', 'hv.city_code', 'hv.years', 'hv.price_unit_avg as average_price', 'hv.cover', 'r1.p_code', 'r1.name as area_name', 'r2.name as city_name'];
        $orderby = ['hv.sale_num' => 'desc','hv.price_unit_avg'=>'asc', 'hv.id' => 'desc'];
        self::sql_list($map, $column, $start, $long, $orderby, '', $page, $pageNum, $data, $count);
    }

    /**
     * 小区列表sql
     * @param $map
     * @param $column
     * @param $start
     * @param $long
     * @param $orderby
     * @param $page
     * @param $pageNum
     * @param $data
     * @param $count
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function sql_list($map, $column, $start, $long, $orderby, $orderRaw, &$page, &$pageNum, &$data, &$count) {
        $data = db("house_village")
            ->alias('hv')
            ->leftJoin('region r1', 'r1.city_code=hv.city_code')
            ->leftJoin('region r2', 'r2.city_code=r1.p_code')
            ->where($map)
            ->field($column)
            ->order($orderby);
        if ($orderRaw) {
            $data->orderRaw("field(hv.id,{$orderRaw})");
        }
        $data = $data->page($start, $long)
            ->select();
        $page = $start;
        $count = db("house_village")
            ->alias('hv')
            ->leftJoin('region r1', 'r1.city_code=hv.city_code')
            ->leftJoin('region r2', 'r2.city_code=r1.p_code')
            ->where($map)
            ->count();
        foreach ($data as $k => $datum) {
            $data[$k]['cover'] = empty($data[$k]['cover']) ? config('global.empty_house_village_img') : $data[$k]['cover'];
            $data[$k]['city_area'] = $datum['city_name'] . '-' . $datum['area_name'];
            unset($data[$k]['city_name']);
            unset($data[$k]['area_name']);
            $data[$k]['years'] = !empty($data[$k]['years']) ? $data[$k]['years'] : '';

            $data[$k]['average_price'] = !empty($data[$k]['average_price']) ? (string)$data[$k]['average_price'] : '';

            unset($data[$k]['city_code']);
            unset($data[$k]['p_code']);
        }
        if ($long > 0) {
            $pageNum = ceil($count / $long);
        } else {
            $pageNum = 1;
        }
    }

    /**
     * 获取小区房源详情
     * @param $id
     * @return mixed
     */
    static function get_detail($id, $headers) {
        $column = ['hv.price_unit_avg as average_price',
            'hv.address', 'hv.cost', 'hv.years',
            'hv.parking_space', 'hv.plot_ratio',
            'hv.developers', 'hv.greening_rate', 'hv.tenement',
            'hv.name as hv_name', 'hv.city_code', 'hv.cover',
            'hv.property as htname', 'hv.acreage', 'hv.person_num',
            'hv.trading_ownership','hv.water_type','hv.electricity_type',
            'hv.heating_type','hv.gas_fee','hv.total_build','hv.related_school','hv.business_name'];
        $data = Db::name('house_village')
            ->alias('hv')
            ->join('house h', 'h.village_id = hv.id', 'LEFT')
            ->join('house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->field($column)
            ->find($id);
        $regions = Region::getUp_city($data['city_code']);
        $data['cover'] = empty($data['cover']) ? config('global.empty_house_village_img') : $data['cover'];
        $data['city_area'] = $data['address'];
        $data['average_price'] = !empty($data['average_price']) ? (string)$data['average_price'] : '';
        if (isset($headers['token'])) {
            $Token = new Token();
            $tokens = $Token->verifyToken($headers['token'], $headers['devsn'], $Token::API_TOKEN, RedisKey::APP_TOKEN_HASH);
            if (empty($tokens)) {
                $data['isRemind'] = 0;//未提醒
            } else {
                $params['agent_id'] = $tokens['id'];
                $params['id'] = $id;
                $isRemind = AgentRemind::isRemind($params, 2);
                if (!empty($isRemind)) {
                    $data['isRemind'] = 1;//已提醒
                } else {
                    $data['isRemind'] = 0;//未提醒
                }
            }
        } else {
            $data['isRemind'] = 0;//未提醒
        }

        unset($data['address']);
        $arr= self::getHouseVillageAuction($id);
        $data['total_num']=$arr['total_num'];//拍卖总套数
        $data['sale_num']=$arr['sale_num'];//正在拍卖或即将拍卖房源数
        $data['finish_num']=$arr['finish_num'];//已结束房源
        return $data;
    }

    /**
     * 小区对应房源
     * @param $id
     * @param $start
     * @param $long
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    static public function get_village_house($params) {
        $House = new House();
        $column = array_merge($House->houseFields, $House->villageFields, $House->typeFields, $House->auctionFields,$House->businessFields,$House->reginFields);
        $map[] = ['h.village_id', '=', intval($params['village_id'])];
        $orderby = ['ha.auction_status' => 'asc', 'h.id' => 'desc'];
        $map[] = ['h.is_shelf', '=', 1];
        $long=20;
        $start=1;
        $re = $House->house_list($map, '', $column, $start, $long, $orderby, '');
        $re[0] = House::house_list_style($re[0]);
        return $re;
    }

    /**
     *购房需求-小区
     */
    public static function getV($params) {
        return self::where('city_code', 'in',$params['city_code'])->field('name,id')->select()->toArray();
    }

    /**
     * 定制选房->小区数据
     * @param $params
     * @param $pageSize
     * @return bool
     */
    public function getVillageList($params,$pageSize) {
        $where=[];
        if ($params['area_code']!=$params['city_code'].'_all'){
            //选择区域传入
            $codes=explode(',',$params['area_code']);
            if (count($codes)>5){
                Err::add('区域选择不能超过5个',RespCode::PARAMS_ERR);
                return false;
            }
            $where[]=['city_code','in',$codes];
        }else{
            //不限制区域
            $p_code=db('region')->where('city_code',$params['city_code'])->value('p_code');
            $where[]=['city_codes','like', ','.$p_code.','.$params['city_code'] . '%'];
        }

        //小区名称模糊匹配
        if (isset($params['keywords'])&&$params['keywords']){
            $keywords=trim($params['keywords']);
            $where[]=['name','like', '%'.$keywords . '%'];
        }
        //查询分页数据
        $data=db('house_village')
            ->field('name,id')
            ->page($params['page'],$pageSize)
            ->where($where)
            ->select();
        //数据总数
        $count=db('house_village')
            ->where($where)
            ->count();
        $list['count'] = $count ?? 0;//数据总条数
        $list['page'] = (int)$params['page'];//当前页码
        $list['pageSize'] = $pageSize;//每页显示条数
        $list['pageNum'] = ceil($list['count'] / $pageSize);//每页显示条数
        $list['list'] = $data ? $data : [];//每页显示数据
        return $list;
    }
    /**
     * 获取小区名
     * @param $id
     * @return mixed
     */
    public static function get_Name($id) {
        return Db::name('house_village')->where('id', $id)->value('name');
    }

    /**
     * 统计小区拍卖房源总数/已结束套数/即将或正在进行数
     * @param $id
     */
    public static function getHouseVillageAuction($id){
        //小区拍卖房源总数
        $total_num=db('house')
            ->alias('h')
            ->join('erp_house_village hv','hv.id=h.village_id','left')
            ->join('erp_house_auction ha','ha.id=h.auction_id','left')
            ->where("h.is_shelf=1 and h.deleted=0 and h.village_id={$id} and h.is_update=1 and ha.type is not null")
            ->count();
        //即将或正在进行的房源数
        $sale_num=db('house')
            ->alias('h')
            ->join('erp_house_village hv','hv.id=h.village_id','left')
            ->join('erp_house_auction ha','ha.id=h.auction_id','left')
            ->where("h.is_shelf=1 and h.deleted=0 and h.village_id={$id} and h.is_update=1 and ha.type is not null and ha.auction_status in (1,2)")
            ->count();
        //已结束房源
        if($total_num>$sale_num){
            $finish_num = $total_num-$sale_num;
        }else{
            $finish_num=0;
        }
        return ['total_num'=>$total_num,'sale_num'=>$sale_num,'finish_num'=>$finish_num];
    }
}
